package com.kpl.kplstzble.fragment;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.CoordinateConverter;
import com.amap.api.location.DPoint;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.example.chezaicm.b;
import com.kpl.kplstzble.R;
import com.kpl.kplstzble.activity.HomeActivity;
import com.kpl.kplstzble.database.MySqliteOpenHelper;
import com.kpl.kplstzble.interf.FragmentBackHandler;
import com.kpl.kplstzble.utils.AMapUtil;
import com.kpl.kplstzble.utils.BackHandlerHelper;
import com.kpl.kplstzble.utils.DBUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;


public class MeasureFragment extends Fragment implements FragmentBackHandler,CompoundButton.OnCheckedChangeListener,LocationSource,AMapLocationListener  {
    private MapView mapView;
    private View mapLayout;
    public static AMap aMap;
    private AMapLocationClient locationClient;
    private AMapLocationClientOption clientOption;
    private OnLocationChangedListener mListener;
    private static MeasureFragment fragment=null;
    private ToggleButton btn_mapchange;
    private Button btn_finish;
    private Button btn_pause;
    public static TextView showarea;
    public static TextView showspeed;
    public static TextView showdistance;
    public static List<LatLng> latLngs = new ArrayList<LatLng>();
    public static List datalist = new ArrayList();
    public static LatLng curruentpoint;
    public static Double sumdistance=0.0;
    public static b cm_ff;
    private  static String thisdevicename;
    public  static int flagthis;
    public static int workstatus=0;//0表示正在工作  1表示暂停测量 2表示停止测量
    public static int realtimemacwidththis;//实时车载宽幅
    public static int surroundmacwidththis;//绕圈车载边距
    public  static double munum;//测量数据
    private long starttime;
    private long endtime;
    private  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SQLiteDatabase db;

    MeasureFragment(String devicename,int flag, int realtimemacwidth, int surroundmacwidth){
        if(fragment==null){
            synchronized(MeasureFragment.class){
                if(fragment==null){
                    workstatus=0;
                    flagthis=flag;
                    thisdevicename=devicename;
                    realtimemacwidththis=realtimemacwidth;
                    surroundmacwidththis=surroundmacwidth;
                }
            }
        }
    }
    @Override
    public boolean onBackPressed() {
        if(workstatus!=0){
            Toast.makeText(getActivity(), "请先结束测量！", Toast.LENGTH_SHORT).show();
        }
        return BackHandlerHelper.handleBackPress(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        SQLiteOpenHelper instance = MySqliteOpenHelper.getInstance(getContext());
        db = instance.getReadableDatabase();
        //初始化定位  用户合规检查
        AMapLocationClient.updatePrivacyShow(getContext(), true, true);
        AMapLocationClient.updatePrivacyAgree(getContext(), true);
        if (mapLayout == null) {
            mapLayout = inflater.inflate(R.layout.page_measure, null);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+08")); //设置时区
            btn_mapchange=(ToggleButton) mapLayout.findViewById(R.id.mapchange);
            btn_mapchange.setOnCheckedChangeListener(this);
            showarea=(TextView) mapLayout.findViewById(R.id.showarea);
            showspeed=(TextView) mapLayout.findViewById(R.id.speed);
            showdistance=(TextView) mapLayout.findViewById(R.id.distance);
            mapView = (MapView) mapLayout.findViewById(R.id.measuremap);
            mapView.onCreate(savedInstanceState);
            if (aMap == null) {
                aMap = mapView.getMap();
            }
            aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 设置卫星地图模式，aMap是地图控制器对象。
            //aMap.getUiSettings().setAllGesturesEnabled(false);//禁止地图可拖动
            //设置缩放级别
            aMap.moveCamera(CameraUpdateFactory.zoomTo(20));
            //显示定位层并可触发，默认false,显示定位蓝点
            //aMap.setMyLocationEnabled(true);
            cm_ff = new b();
            double area = cm_ff.CM_START(realtimemacwidththis, 0);
            showarea.setText(area+"");
            //开始接收测量数据
            starttime=System.currentTimeMillis();
            btn_pause=(Button) mapLayout.findViewById(R.id.btn_pause);
            btn_pause.setOnClickListener(view -> {
                if(workstatus==1){//已经暂停
                    btn_pause.setText("暂停测量");
                    workstatus=0;
                    HomeActivity.read("继续测量");
                }else if(workstatus==0){
                    btn_pause.setText("继续测量");
                    workstatus=1;
                    HomeActivity.read("暂停测量");
                }
            });
            btn_finish=(Button) mapLayout.findViewById(R.id.btn_finish);//结束量地
            btn_finish.setOnClickListener(view -> {
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setMessage("您确定要结束本次测量吗？");
                builder.setCancelable(false);
                builder.setPositiveButton("结束测量", (dialog, id) -> {
                    HomeActivity.read("结束测量");
                    if (flagthis == 0) {//实时测量
                        munum = (double) Math.round(cm_ff.CM_END()) / 100/*+sumdistance*surroundmacwidththis*/;
                    }
                    endtime = System.currentTimeMillis();
                    String datestring = sdf.format(endtime);
                    int datediffer;
                    if ((endtime - starttime) % (1000 * 60) == 0) {
                        datediffer = (int) ((endtime - starttime) / (1000 * 60));//两个时间分钟差
                    } else {
                        datediffer = (int) ((endtime - starttime) / (1000 * 60)) + 1;//两个时间分钟差
                    }
                    new Thread(
                            () -> {
                                boolean savedata = DBUtils.savedata(thisdevicename, datalist.toString(), String.format("%.2f", munum), sumdistance.toString(), datestring, datediffer, flagthis);
                                if (!savedata) {//存储服务器失败，先存入本地
                                    if (db.isOpen()) {
                                        //Cursor users = db.rawQuery("select * from users", null);
                                        Cursor users = db.query("historydata", null, null, null, null, null, null);
                                        ContentValues values = new ContentValues();
                                        values.put("datainfo", datalist.toString());
                                        values.put("munum", String.format("%.2f", munum));
                                        values.put("distance", sumdistance);
                                        values.put("date", datestring);
                                        values.put("datediffer", datediffer);
                                        values.put("worktype", flagthis);
                                        db.insert("historydata", null, values);
                                        db.close();
                                    }
                                }
                            }
                    ).start();
                    FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                    HomeFragment homeFragment = new HomeFragment();
                    //ft.hide(this).remove(this)/*.show(HomeActivity.cmFragment)*/.commit();
                    ft.hide(this).remove(this).show(homeFragment).commit();



                });
                builder.setNegativeButton("再想想", (dialog, id) -> dialog.cancel());
                AlertDialog alert = builder.create();
                alert.show();

            });
        }else {
            if (mapLayout.getParent() != null) {
                ((ViewGroup) mapLayout.getParent()).removeView(mapLayout);
            }
        }
        return mapLayout;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }
    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener=listener;
        if(locationClient==null){
            try {
                locationClient=new AMapLocationClient(getActivity());
                clientOption=new AMapLocationClientOption();
                clientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//高精度定位
                //clientOption.setOnceLocationLatest(true);//设置单次精确定位
                locationClient.setLocationOption(clientOption);
                locationClient.startLocation();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void deactivate() {
        mListener=null;
        if(locationClient!=null){
            locationClient.stopLocation();
            locationClient.onDestroy();
        }
        locationClient=null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

    }
    private void addMarker(boolean visible, List<LatLng> latLnglist) {
        ArrayList<MarkerOptions> options = new ArrayList<>();
        for (LatLng latLng : latLnglist) {
            // 在地图上添一组图片标记（marker）对象，并设置是否改变地图状态以至于所有的marker对象都在当前地图可视区域范围内显示
            MarkerOptions markerOptions = new MarkerOptions();

            // 设置Marker覆盖物的位置坐标。Marker经纬度坐标不能为Null，坐标无默认值
            markerOptions.position(latLng);
            // 设置Marker覆盖物是否可见
            markerOptions.visible(visible);
            // 设置Marker覆盖物是否可拖拽
            markerOptions.draggable(visible);
            options.add(markerOptions);
        }
        // 在地图上添一组图片标记（marker）对象，并设置是否改变地图状态以至于所有的marker对象都在当前地图可视区域范围内显示
        aMap.addMarkers(options, true);
    }
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        if(isChecked){
            aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
        }
        else {
            aMap.setMapType(AMap.MAP_TYPE_NORMAL);
        }
    }
    /**
     * 计算任意多边形的面积
     * @param latLngLines 经纬度坐标点
     * @return
     */
    public static float calculateArea(List<LatLng> latLngLines) {
        List<double[]> pointFList = new ArrayList<>();
        for (int i = 0; i < latLngLines.size(); i++) {
            LatLng latLng = latLngLines.get(i);
            //经纬度转换成平面直角坐标系
            pointFList.add(AMapUtil.WGS2flat(latLng.longitude, latLng.latitude));
        }

        int iCycle, iCount;
        double iArea = 0;
        iCount = pointFList.size();
        for (iCycle = 0; iCycle < iCount; iCycle++) {
            iArea = iArea + (pointFList.get(iCycle)[0] * pointFList.get((iCycle + 1) % iCount)[1] - pointFList.get((iCycle + 1) % iCount)[0] * pointFList.get(iCycle)[1]);
        }
        return (float) Math.abs(0.5 * iArea);
    }

    public static AMapLocation fromGpsToAmap(Location location) {
        AMapLocation aMapLocation = new AMapLocation(location);
        CoordinateConverter converter = new CoordinateConverter(HomeActivity.context);
        converter.from(CoordinateConverter.CoordType.GPS);
        try {
            converter.coord(new DPoint(location.getLatitude(), location.getLongitude()));
            DPoint desLatLng = converter.convert();
            aMapLocation.setLatitude(desLatLng.getLatitude());
            aMapLocation.setLongitude(desLatLng.getLongitude());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aMapLocation;
    }


    public static void drawmap(String strString){
        /* 经度 */
        BigDecimal bgLongitude = BigDecimal.valueOf(Double.longBitsToDouble(Long.parseLong(strString.substring(0,2), 16)));
        double longitude = bgLongitude.setScale(6, RoundingMode.HALF_UP).doubleValue();

        /* 纬度 */
        BigDecimal bglatitude = BigDecimal.valueOf(Double.longBitsToDouble(Long.parseLong(strString.substring(14, 22), 16)));
        double latitude = bglatitude.setScale(6, RoundingMode.HALF_UP).doubleValue();

        //速度
        float speed = hextransflaot(strString.substring(28, 36));

        Location targetLocation = new Location("");//provider name is unnecessary
        targetLocation.setLatitude(longitude);//your coords of course
        targetLocation.setLongitude(latitude);
        AMapLocation aMapLocation = fromGpsToAmap(targetLocation);
        double latitude2 = new BigDecimal(aMapLocation.getLatitude()).setScale(6, BigDecimal.ROUND_DOWN).doubleValue();
        double longitude2 = new BigDecimal(aMapLocation.getLongitude()).setScale(6, BigDecimal.ROUND_DOWN).doubleValue();
        
        if(latitude2==0||longitude2==0){
            latitude2=34.803613;
            longitude2=113.529513;
        }
        //aMap.clear();
        LatLng latLng0 = new LatLng(latitude2,longitude2);
        final Marker marker = aMap.addMarker(new MarkerOptions().position(latLng0).title("电子").snippet("车辆标记").icon(BitmapDescriptorFactory.fromResource(R.drawable.tlj48)));
        //计算行驶路程
        if(curruentpoint!=null){
            double distance =AMapUtils.calculateLineDistance(curruentpoint,new LatLng(latitude2,longitude2));
            sumdistance+=distance;
            //System.out.println("本次点位距离："+distance);
        }
        sumdistance= new BigDecimal(sumdistance).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
        curruentpoint = new LatLng(latitude2,longitude2);
        aMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(latitude2,longitude2)));
        latLngs.add(new LatLng(latitude2,longitude2));
        String  arr = latitude2+"&"+longitude2;
        datalist.add(arr);
        aMap.addPolyline(new PolylineOptions().addAll(latLngs).width(20).color(Color.argb(255, 255, 255, 255)));
        if(flagthis==0){//实时测量
            byte E = 'E';
            byte N = 'N';
            munum = cm_ff.CM_JWD((long)(latitude*1000000), E, (long)(longitude*1000000), N, (long)(speed*1000));
            showarea.setText((double)Math.round(munum)/100+"");
            showspeed.setText(speed+"");
            showdistance.setText(sumdistance+"");
        }else if(flagthis==1){//绕圈测量
            // 定义多边形的属性信息
            PolygonOptions polygonOptions = new PolygonOptions();
            // 添加多个多边形边框的顶点
            for (LatLng latLng : latLngs) {
                polygonOptions.add(latLng);
            }
            // 设置多边形的边框颜色，32位 ARGB格式，默认为黑色
            polygonOptions.strokeColor(Color.argb(0, 225, 225, 225));
            // 设置多边形的边框宽度，单位：像素
            polygonOptions.strokeWidth(5);
            // 设置多边形的填充颜色，32位ARGB格式
            polygonOptions.fillColor(Color.argb(100, 34, 139, 34)); // 注意要加前两位的透明度
            // 在地图上添加一个多边形（polygon）对象
            aMap.addPolygon(polygonOptions);
            double cemunum = calculateArea(latLngs);
            cemunum=cemunum+(sumdistance*surroundmacwidththis/20);
            munum=(double)Math.round((cemunum/666)*100)/100;
            showarea.setText(munum+"");
            showspeed.setText(speed+"");
            showdistance.setText(sumdistance+"");
            //addMarker(true,latLngs);
        }
    }

    public static float hextransflaot(String hexData) {
        int length = hexData.length();
        byte[] byteData = new byte[length / 2];

        for (int i = 0; i < length; i += 2) {
            byteData[i / 2] = (byte) ((Character.digit(hexData.charAt(i), 16) << 4)
                    + Character.digit(hexData.charAt(i + 1), 16));
        }
        int intValue = (byteData[0] & 0xFF) << 24
                | (byteData[1] & 0xFF) << 16
                | (byteData[2] & 0xFF) << 8
                | (byteData[3] & 0xFF);
        return Float.intBitsToFloat(intValue);
    }
}
